package com.et.u1

import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.et.core.goods.GoodsProvider
import com.et.core.init
import com.et.core.release
import com.et.u1.databinding.ActivityMainBinding
import com.et.u1.uitl.ActionBarManager
import com.et.u1.uitl.size
import com.et.u1.uitl.discountTypeFace
import com.et.u1.vm.start.InletFragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var mainModel: MainModel
    private lateinit var binding: ActivityMainBinding
    private lateinit var actionBarManager: ActionBarManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        CoroutineScope(Dispatchers.IO).launch { init(applicationContext) }
        discountTypeFace = Typeface.createFromAsset(assets, "Hiragino Sans GB W3.otf")
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        mainModel = ViewModelProvider(this).get(MainModel::class.java)
        actionBarManager = ActionBarManager(binding, this)
        mainModel.replaceLiveData.observe(this, {
            Log.d("et_log", "界面切换:")
            supportFragmentManager
                .beginTransaction()
                .setCustomAnimations(
                    R.anim.slide_right_in,
                    R.anim.slide_left_out,
                    R.anim.slide_left_in,
                    R.anim.slide_right_out
                )
                .addToBackStack(null)
                .replace(R.id.container, it)
                .commit()
        })

        binding.home.setOnClickListener {
            for (i in 0 until supportFragmentManager.backStackEntryCount - 2) {
                supportFragmentManager.popBackStack()
            }
        }

        actionBarManager.initActionBar()

        mainModel.initGoodsProvider(this)

        val display = this.windowManager.defaultDisplay
        display?.getSize(size)
    }

    override fun onStart() {
        super.onStart()
        mainModel.replaceLiveData.postValue(InletFragment.newInstance())
    }


    override fun onDestroy() {
        super.onDestroy()
        CoroutineScope(Dispatchers.IO).launch { release(applicationContext) }
        GoodsProvider.getInstance()
        GoodsProvider.getInstance().unregisterContentObserver(this)
    }

}